<template>
  <div class="cs-page-container">
    <div class="cs-filter-container">
      <el-button type="primary" size="small" icon="el-icon-edit" @click="handleList('', 'add')">添加</el-button>
    </div>

    <div class="cs-filter-result">
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        size="small"
        highlight-current-row
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column align="center" label="角色ID">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="角色名称">
          <template slot-scope="scope">
            <span>{{ scope.row.roleName }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="角色描述" width="300">
          <template slot-scope="scope">
            <span>{{ scope.row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建时间" min-width="150">
          <template slot-scope="scope">
            {{
              scope.row.createdAt | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
            }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="更新时间" min-width="150">
          <template slot-scope="scope">
            {{
              scope.row.updatedAt | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
            }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" min-width="160">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleList(scope.row, 'modify')">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleList(scope.row, 'delete')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <TablePagination
        :current-page="listQuery.page"
        :limit="listQuery.limit"
        :total="total"
        :loading="listLoading"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>

    <el-dialog :title="operationFormTitle" :visible.sync="operationFormVisible">
      <el-form
        ref="operationInfo"
        :rules="rules"
        class="small-space"
        :model="operationInfo"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="operationInfo.roleName" :disabled="operationInfo.type == 'modify'" />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input v-model="operationInfo.description" />
        </el-form-item>

        <el-form-item ref="permissionIdList" label="角色权限" prop="permissionIdList">
          <el-tree
            ref="tree"
            highlight-current
            :data="treeData"
            show-checkbox
            :default-expanded-keys="treeExpandId"
            expand-on-click-node
            :check-on-click-node="true"
            node-key="id"
            @check="nodeClick"
          />
          <el-input v-model="operationInfo.permissionIdList" style="display: none" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="operationFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TablePagination from '@/components/TablePagination'

import {
  xhrGetRoleList,
  xhrGetPermissionList,
  xhrDelRole,
  xhrAddRole,
  xhrEditRole
} from '@api/system'
export default {
  name: 'RoleList',
  components: { TablePagination },
  data() {
    return {
      list: null,
      total: 0,
      listQuery: {
        offset: 0,
        limit: 10,
        page: 1
      },
      treeData: [],
      checkedNodeIds: [],
      treeExpandId: [],
      operationFormTitle: '',
      operationFormVisible: false,
      operationInfo: {},
      addFormVisible: false,
      channelOptions: [],
      roleOptions: [],
      rules: {
        roleName: [{ required: true, message: '不能为空', trigger: 'change' }],
        description: [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        permissionIdList: [
          { required: true, message: '不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.doSearch()
    this.getTreeData()
  },
  methods: {
    doSearch() {
      this.listLoading = true
      this.listQuery.offset = (this.listQuery.page - 1) * this.listQuery.limit
      xhrGetRoleList(this.listQuery)
        .then(resp => {
          this.list = resp.data.items
          this.total = resp.data.count
          this.listLoading = false
        })
        .catch(err => {
          this.$message.error(err)
          this.listLoading = false
        })
    },
    getTreeData() {
      xhrGetPermissionList().then(resp => {
        this.treeData = resp.data.items
        this.treeData.forEach(item => this.treeExpandId.push(item.id))
      })
    },
    nodeClick() {
      const checkedNodes = this.$refs.tree.getCheckedNodes(false, true)
      this.checkedNodeIds = []
      for (const item of checkedNodes) {
        this.checkedNodeIds.push(item['id'])
      }
      this.operationInfo.permissionIdList = this.checkedNodeIds.join(',')
    },
    resetTree() {
      this.$refs.tree.setCheckedKeys([])
    },
    handleList(row, type) {
      if (type === 'add' || type === 'modify') {
        this.operationFormVisible = true
        if (type === 'add') {
          this.$nextTick(() => {
            this.resetTree()
            this.operationFormTitle = '新增角色'
            this.operationInfo = {
              type: 'add',
              roleName: '',
              description: '',
              permissionIdList: ''
            }
            this.$refs['operationInfo'].resetFields()
          })
        } else {
          this.$nextTick(() => {
            this.operationFormTitle = '编辑'
            this.treeExpandId = row.permissionIdList
            this.$refs.tree.setCheckedKeys(row.permissionIdList)
            this.operationInfo = {
              type: 'modify',
              id: row.id,
              roleName: row.roleName,
              description: row.description,
              permissionIdList: row.permissionIdList.join(',')
            }
          })
        }
      } else {
        this.$confirm(`确认删除此角色？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          xhrDelRole({ id: row.id }).then(resp => {
            if (resp.code === 0) {
              this.doSearch()
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.operationFormVisible = false
            } else {
              this.$message({
                message: resp.msg,
                type: 'error'
              })
            }
          })
        })
      }
    },
    confirm() {
      this.nodeClick()
      this.$refs['operationInfo'].validate(valid => {
        if (valid) {
          const params = {
            description: this.operationInfo.description,
            excludeHalfCheckedPermissionIds: this.checkedNodeIds
          }

          if (this.operationInfo.type === 'add') {
            params.roleName = this.operationInfo.roleName
            xhrAddRole(params).then(resp => {
              if (resp.code === 0) {
                this.doSearch()
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.operationFormVisible = false
              } else {
                this.$message({
                  message: resp.msg,
                  type: 'error'
                })
              }
            })
          }
          if (this.operationInfo.type === 'modify') {
            params.id = this.operationInfo.id
            xhrEditRole(params).then(resp => {
              if (resp.code === 0) {
                this.doSearch()
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.operationFormVisible = false
                location.reload()
              } else {
                this.$message({
                  message: resp.msg,
                  type: 'error'
                })
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
